﻿using UnityEngine;


namespace Manox.Libs.Networking
{
    /// <summary>
    /// Unity message packer.
    /// </summary>
    public class MessagePacker
    {
        /// <summary>
        /// Pack message.
        /// </summary>
        /// <param name="message"></param>
        /// <param name="data"></param>
        /// <param name="length"></param>
        /// <returns></returns>
        public static bool Pack(NetworkMessage message, out byte[] data, out int length)
        {
            SerializeWriter writer = new SerializeWriter();

            byte dataType = NetworkMessageTranslator.Instance.GetTypeId(message.GetType());

            writer.Write(dataType);

            message.Serialize(writer);

            data = writer.ToArray();
            length = writer.Position;

            return true;
        }

        /// <summary>
        /// Unpack message.
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public static NetworkMessage Unpack(byte[] data)
        {
            SerializeReader reader = new SerializeReader(data);

            byte dataType = reader.ReadByte();

            NetworkMessage message = NetworkMessageTranslator.Instance.GetInstance(dataType) as NetworkMessage;

            if (message == null)
            {
                Debug.Log("Unknown type");

                return null;                
            }

            message.Deserialize(reader);

            return message;
        }
    }
}
